<template>
  <div class="container">
    <div class="app-container">
      <el-tree :data="depts" :props="{ label: 'name' }" default-expand-all :expand-on-click-node="false">
        <template #default="{ data }">
          <el-row :style="{ width: '100%' }" type="flex" justify="space-between">
            <div>{{ data.name }}</div>
            <el-row style="width: 140px;" type="flex" justify="space-between">
              <span>{{ data.managerName }}</span>
              <el-dropdown @command="onOperation($event, data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>

          </el-row>
        </template>
      </el-tree>
    </div>
    <AddDep :visible.sync="visible" :current-node-id="currentNodeId" @getDepts="getDepts" />
  </div>
</template>
<script>
import { deleteDepartment, getDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils'
import AddDep from './AddDep.vue'

export default {
  name: 'Department',
  components: {
    AddDep
  },
  data() {
    return {
      isEdit: false,
      depts: [],
      visible: false,
      currentNodeId: null,
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getDepts()
  },
  methods: {
    openConfirm(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delDepartment(id)
      })
    },
    async  getDepts() {
      const res = await getDepartment()
      this.depts = transListToTreeData(res, 0)
    },
    async delDepartment(id) {
      await deleteDepartment(id)
      this.$message.success('删除成功')
      this.getDepts()
    },
    async onOperation(command, id) {
      this.currentNodeId = id
      if (command === 'add') {
        this.isEdit = false
        this.visible = true
      } else if (command === 'edit') {
        this.isEdit = true
        this.visible = true
        this.$nextTick(() => {
          this.$refs.addDept.getDepartmentDetail(id)
        })
      } else if (command === 'del') {
        this.openConfirm(id)
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 30px 100px;
  font-size: 14px;
}

.tree-manager {
  width: 80px;
  display: inline-block;
  margin: 10px;
}
</style>
